#include <QApplication>
#include <QMovie>
#include <QDebug>
#include <QTimer>
#include <QScreen>
#include <QMouseEvent>
#include <QThread>

#include "new_pop_window.h"
#include "ui_new_pop_window.h"
#include "size_para.h"
#include "ukui_printer.h"
#include "pop_window_manager.h"
#include "gsettings_monitor.h"
#include "global_variable.h"

NewPopWindow::NewPopWindow(const DeviceInformation &info, QWidget *parent)
  : m_popDevInfo(info),
    CustomTransWidget(parent),
    m_ui(new Ui::NewPopWindow)
{
    initUi();
    initConnection();
    installEventFilter(this);
    setDevInfo(m_popDevInfo.name);
}

void NewPopWindow::initUi()
{
    m_ui->setupUi(this);
    this->setProperty("useStyleWindowManager", false);
    this->setAttribute(Qt::WA_DeleteOnClose);

    this->setWindowFlags(Qt::Tool);

    /* 标题栏 */
    m_ui->titlePictureBtn->setFlat(true);
    m_ui->titlePictureBtn->setStyleSheet("border-radius:4px;");

    m_ui->appNameLabel->setText(tr("Printer"));

    m_ui->closeButton->setProperty("isWindowButton", 0x2);
    m_ui->closeButton->setProperty("useIconHighlightEffect", 0x4);
    m_ui->closeButton->setFlat(true);
    m_ui->closeButton->setAttribute(Qt::WA_TranslucentBackground, true);


    /* 主体窗口 */
    m_ui->picButton->setFlat(true);
    m_ui->picButton->setStyleSheet("border-radius:4px;");

    QMovie *movieLoading = new QMovie(":/main_win_ui/loading.gif");
    movieLoading->setScaledSize(QSize(24,24));
    m_ui->loadPic->setMovie(movieLoading); //初始默认图片0
    movieLoading->start();


    /* 底部按钮 */
    m_ui->printTestBtn->setText(tr("Print Test Page"));
    m_ui->deviceViewButton->setText(tr("View Device"));
    m_ui->manualInstallBtn->setText(tr("Manual Install"));

    /* 位置设置 */
    QScreen *screen = QGuiApplication::primaryScreen();
    this -> move(screen->geometry().topRight().x() - this->width(),
                    screen->geometry().topRight().y());//插拔时始终在右上角

    m_failTimeout = new QTimer(this);
    connect(m_failTimeout,&QTimer::timeout,this,&NewPopWindow::onShowFailed);
    m_failTimeout->setSingleShot(true);

    m_succeedTimeout = new QTimer(this);
    connect(m_succeedTimeout,&QTimer::timeout,this,&NewPopWindow::onExit);
    m_succeedTimeout->setSingleShot(true);

    UKUI_WIN_CONTROL_PROTOOL(this);
}


void NewPopWindow::initConnection()
{
    connect(m_ui->printTestBtn,&QPushButton::clicked, this, [=]() {
        printTestMessageShow();
        this->close();
    });

    connect(m_ui->manualInstallBtn,&QPushButton::clicked, this, [=]() {
        emit PopWindowManager::getInstance()->manualInstallShowRequest(m_popDevInfo);
        this->close();
    });

    connect(m_ui->deviceViewButton,&QPushButton::clicked, this, [=]() {
        // emit deviceViewRequest();
        emit PopWindowManager::getInstance()->deviceViewShowRequest(m_popDevInfo.name);
        this->close();
    });

    connect(m_ui->closeButton, &QPushButton::clicked, this, [=]() {
        if (this->m_popWinStu == PopWinStatus::INSTALLING) {
            this->hide();
        }
        else
            this->close();
    });
}

NewPopWindow::~NewPopWindow()
{
    qDebug() << "NewPopWindow:" << m_popDevInfo.name <<" delete, show next";
    m_succeedTimeout->stop();
    m_failTimeout->stop();
    if (m_ui != nullptr) {
        delete m_ui;
        m_ui = nullptr;
    }
    emit PopWindowManager::getInstance()->showNextRequest();
}

void NewPopWindow::Show(const PopWinStatus &stu)
{
    switch (stu)
    {
    case (PopWinStatus::INSTALLING) :
        if (this->m_popWinStu != PopWinStatus::HIDE) {
            break ;
        }
        // turn to Installing
        m_ui->isInstallLabel->setText(tr("Installing......"));
        m_ui->printTestBtn->hide();
        m_ui->deviceViewButton->hide();
        m_ui->manualInstallBtn->hide();
        this->show();
        this->m_popWinStu = stu;
        m_failTimeout->start(60000);
        break ;
    case (PopWinStatus::INSTALL_SUCCESS) :
        if (this->m_popWinStu != PopWinStatus::INSTALLING
         && this->m_popWinStu != PopWinStatus::HIDE      ) {

            break;
        }
        // TODO: turn to success;
        m_ui->isInstallLabel->setText(tr("Successful installation!"));
        m_ui->loadPic->hide();
        m_ui->printTestBtn->show();
        m_ui->deviceViewButton->show();
        if (this->isHidden()) {
            this->show();
        } 
        else {
            this->update();
        }
        this->m_popWinStu = stu;
        m_succeedTimeout->start(5000);
        m_failTimeout->stop();
        break ;
    case (PopWinStatus::INSTALL_FAIL) :
        if (this->m_popWinStu != PopWinStatus::INSTALLING
         && this->m_popWinStu != PopWinStatus::HIDE      ) {
        
            break ;
        }
        // TODO: turn to fail;
        m_ui->isInstallLabel->setText(tr("Installation failed!"));
        m_ui->loadPic->hide();
        m_ui->manualInstallBtn->show();
        if (this->isHidden()) {
            this->show();
        } 
        else {
            this->update();
        }
        this->m_popWinStu = stu;
        m_failTimeout->stop();
        break ;
    default :
        break ;
    }
    return ;
}

void NewPopWindow::setDevInfo(const QString &printerName)
{
    if (printerName.isEmpty()) {
        qDebug() << "Cannot get printerName!";
        return ;
    }
    QString totalName = tr("Printer Detected:") + printerName;
    m_ui->isMonitorLabel->setText(totalName);

    return ;
}

void NewPopWindow::printTestMessageShow()
{
    bool res = false;
    res = UkuiPrinterManager::getInstance().printTestPage(m_popDevInfo.name);
    if (this->m_popWinStu != PopWinStatus::INSTALL_SUCCESS) {
        return ;
    }
    // 点了打印测试页就停止计时
    m_succeedTimeout->stop();
    if(res)
    {
        CustomMessageBox msg2(CustomMessageBox::Question,tr("Hint"), tr("Is the test page printed successfully?"), CustomMessageBox::NoButton);
        QPushButton *btnYes = msg2.addButton(tr("Yes"), CustomMessageBox::YesRole);
        QPushButton *btnNo  = msg2.addButton(tr("No"), CustomMessageBox::NoRole);
        msg2.exec();
        if ((QPushButton*)msg2.clickedButton() == btnYes) {
            return;
        } else if ((QPushButton*)msg2.clickedButton() == btnNo) {
            CustomMessageBox msg3(CustomMessageBox::Question,tr("Hint"), tr("Test print failed.Do you want to change a printer driver?"), CustomMessageBox::NoButton);
            QPushButton *btnYes = msg3.addButton(tr("Change Driver"), CustomMessageBox::YesRole);
            QPushButton *btnNo  = msg3.addButton(tr("Cancel"), CustomMessageBox::NoRole);
            msg3.exec();
            if ((QPushButton*)msg3.clickedButton() == btnYes) {
                emit manualInstallRequest();
                return;
            } else if ((QPushButton*)msg3.clickedButton() == btnNo) {
                return;
            }
        }
    }
    else
    {
        m_msg = new CustomMessageBox(CustomMessageBox::Critical,tr("Error"),tr("Failed to start, please try to add the printer again!"),CustomMessageBox::Yes);

    }
    m_msg->button(CustomMessageBox::Yes)->setText(tr("Ok"));
    QTimer::singleShot(5000, m_msg, SLOT(close));
    m_msg->exec();
}

PopWinStatus NewPopWindow::getPopWinStatus() const
{
    return m_popWinStu;
}

void NewPopWindow::onShowFailed()
{
    qDebug() << "In Installing: " << m_popDevInfo.name << " ,time out!";
    if(getPopWinStatus() != PopWinStatus::INSTALL_SUCCESS)
    {
        Show(PopWinStatus::INSTALL_FAIL);
    }
}

void NewPopWindow::onExit()
{
    this->~NewPopWindow();
}
